package korkd.tower;

import java.util.Random;

import org.anddev.andengine.entity.layer.tiled.tmx.TMXLayer;
import org.anddev.andengine.entity.layer.tiled.tmx.TMXProperty;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.path.ITiledMap;
import org.anddev.andengine.util.path.Path;
import org.anddev.andengine.util.path.astar.AStarPathFinder;

import android.graphics.Point;
import android.util.Log;

public class Kingdom {

	private static final int CASTLE_COUNT = 8;
	
	private Map mMap;
	private ITiledMap<TMXLayer> mTiledMap;
	private Castle[] mCastles;
	private Path[][] mPaths;

	Kingdom(Map pMap)
	{
		mMap = pMap;
		mCastles = new Castle[CASTLE_COUNT];
		mPaths = new Path[CASTLE_COUNT][CASTLE_COUNT];
		
		Random rand = new Random(System.currentTimeMillis());
		int x = 0, y = 0;
		TMXLayer MapLayer = mMap.getMap().getTMXLayers().get(0);
		
		// Loop through the 8 quadrants of the map
		// 2 columns x 4 rows
		for(int jj = 0; jj < 4; jj++)
		{
			for(int kk = 0; kk < 2; kk++)
			{
				// Loop until each of the four corners of the castle lie on grass tiles
				// Grass GlobalTileID == 40
				do
				{
					// Generate a random number between 2-13 for the y coordinate
					// Multiply jj by 14 to leave a space of 3 tiles at the bottom of the map to allow for a road
					y = (rand.nextInt(12) + 2) + (jj * 14);
					
					// Generate a random number between 2-17 for the x coordinate
					// Multiply kk by 20 to place a castle on the other half of the map
					x = (rand.nextInt(16) + 2) + (kk * 20);
					
				} while(MapLayer.getTMXTile(x-1, y-1).getGlobalTileID() != 40 ||
						MapLayer.getTMXTile(x-1, y+1).getGlobalTileID() != 40 ||
						MapLayer.getTMXTile(x+1, y-1).getGlobalTileID() != 40 ||
						MapLayer.getTMXTile(x+1, y+1).getGlobalTileID() != 40);
				
				Log.i("Castle Placement", "X: " + Integer.toString(x) + " Y: " + Integer.toString(y));
				
				// Generate the castle and offset the center tile since it is placed at its top left corner
				// Multiply by 40 to convert it to pixel coordinates
				mCastles[kk + (jj * 2)] = new Castle((x-1) * 40, (y-2) * 40, Game.TexturePack.get(TextureSheet.CASTLE_ID));
				
				// Generate a road from the castle to a corner of the main road
				mMap.createRoad(mCastles[kk + (jj * 2)]);
				
				// Draw the road
				mMap.drawRoad();
				
				// attach it to the current scene
				SceneManager.INSTANCE.attachToCurrent(mCastles[kk + (jj * 2)]);
				SceneManager.INSTANCE.registerTouchArea(mCastles[kk + (jj * 2)]);
			}
		}
		
		mCastles[0].setControlled(true);
		
		mTiledMap = new ITiledMap<TMXLayer>()
		{
			@Override
			public int getTileColumns() {
				return mMap.getMap().getTileColumns();
			}
			
			@Override
			public int getTileRows()
			{
				return mMap.getMap().getTileRows();
			}
			
			@Override
			public boolean isTileBlocked(TMXLayer pTile, final int pTileColumn, final int pTileRow)
			{
				return false;
			}
			
			@Override
			public float getStepCost(final TMXLayer pTile, final int pFromTileColumn, final int pFromTileRow, final int pToTileColumn, final int pToTileRow)
			{
				TMXProperty cost = pTile.getTMXTile(pToTileColumn, pToTileRow).getTMXTileProperties(mMap.getMap()).get(0);
				return Float.parseFloat(cost.getValue());
				
			}
			
			@Override
			public void onTileVisitedByPathFinder(int pTileColumn, int pTileRow) {
				// Do Nothing
			}
		};
		
		for(int ii = 0; ii < CASTLE_COUNT; ii++)
		{
			if(mCastles[ii] != mCastles[0])
			{
				mPaths[0][ii] = generatePath(mCastles[0], mCastles[ii]);
			}
		}
		
		/*new Thread(new Runnable() {
		    public void run() {
		    	for(Castle c : mCastles)
				{
		    		if(c != mCastles[0])
		    		{
						for(Castle a : mCastles)
						{
							if(c != a)
							{
								c.getCastlePaths().put(a, generatePath(c, a));
							}
						}
		    		}
				}
		    }
		  }).start();
		
		*/
	}
	
	public Path generatePath(Castle pSourceCastle, Castle pDestCastle)
	{
		Path AStarPath;
		
		int FromCol = (int) ((pSourceCastle.getX() + (pSourceCastle.getWidth() / 2)) / 40);
		int FromRow = (int) ((pSourceCastle.getY() + pSourceCastle.getHeight()) / 40);
		int ToCol = (int) ((pDestCastle.getX() + (pDestCastle.getWidth() / 2)) / 40);
		int ToRow = (int) ((pDestCastle.getY() + pDestCastle.getHeight()) / 40);
		
		AStarPathFinder<TMXLayer> AStar = new AStarPathFinder<TMXLayer>(mTiledMap, 3000, false);
		
		AStarPath = AStar.findPath(this.mMap.getMap().getTMXLayers().get(0), 800000, FromCol, FromRow, ToCol, ToRow);
		
		if(AStarPath == null)
		{
			throw new Error("mAPath returned NULL");
		}
		
		return AStarPath;
	}
}
